<template>
  <div class="app-container">

    <!--顶部搜索-->
    <div class="search-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
        <el-form-item prop="id">
          <el-select
            v-model="queryParams.categoryId"
            placeholder="请选择应用分类"
            style="width: 240px"
            clearable
            @change="handleTypeChange"
          >
            <el-option
              v-for="(type, i) in typeList"
              :key="type.categoryId"
              :label="type.categoryName"
              :value="type.categoryId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div class="btn-container">
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-plus"
              @click="handleAdd"
              v-hasPermi="['system:application:add']"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              size="mini"
              @click="handleTypeDlyOpen"
              v-hasPermi="['system:application:type']"
            >分类设置
            </el-button>
          </el-col>

        </el-row>
      </div>
    </div>

    <!--列表-->
    <el-table v-loading="loading" :data="appList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="图片" align="center" prop="dictId">
        <template slot-scope="scope">
          <img :src="getImg(scope.row.icon)" alt="" width="60" height="60">
        </template>
      </el-table-column>
      <el-table-column label="名称" align="center" prop="name" :show-overflow-tooltip="true"/>

      <el-table-column label="应用分类" align="center" prop="status">
        <template slot-scope="scope">
          <span>{{getCategoryType(scope.row.categoryId)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="应用小类" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.application_small_type" :value="scope.row.dictDataId"/>
        </template>
      </el-table-column>
      <el-table-column label="描述" align="center" prop="description" :show-overflow-tooltip="true"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:application:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:application:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页-->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!--新增应用弹窗-->
    <el-dialog
      :title="appTitle"
      :visible.sync="openAppDlg"
      width="870px"
      :close-on-click-modal="false"
      close-on-press-escape
      destroy-on-close
      append-to-body
      @close="resetApp"
    >
      <el-form :model="appForm" :rules="appRules" ref="appForm" labelPosition="top" label-width="80px"
               label-position="right">
        <el-row type="flex" justify="space-around">
          <el-col :span="11">
            <el-form-item label="应用名称" prop="name">
              <el-input v-model="appForm.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="应用分类" prop="categoryId">
              <el-select
                class="form-item"
                v-model="appForm.categoryId"
                placeholder="请选择应用分类"
              >
                <el-option
                  v-for="(type, i) in typeList"
                  :key="type.categoryId"
                  :label="type.categoryName"
                  :value="type.categoryId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <div style="height: 10px"></div>
        <el-row type="flex" justify="space-around">
          <el-col :span="23">
            <el-form-item label="应用图标" prop="icon" style="float: left">
              <!--<div>
                <el-upload
                  class="upload-demo"
                  :action="uploadUrl"
                  :headers="headers"
                  :on-preview="handlePreview"
                  :on-remove="handleRemove"
                  :on-success="handleSuccess"
                  :before-remove="beforeRemove"
                  :on-exceed="handleExceed"
                  :file-list="fileList"
                  :show-file-list="true"
                  :limit="1"
                >
                  <el-button size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                </el-upload>
               <div>
                 <img src="" alt="" width="40" height="40">
                 <span></span>
               </div>
              </div>-->
              <div style="display: flex; align-items: center; justify-content: center">
                <div class="icon-img" v-if="appForm.icon" @mouseover="isHover = true" @mouseleave="isHover = false">
                  <div :class="isHover ? 'del-cover' : 'hide-cover'">
                    <div class="el-icon-delete"  @click="handleRemove"></div>
                  </div>
                  <img
                    class="el-upload-list__item-thumbnail"
                    :src="getImg(appForm.icon)" alt=""
                    width="148" height="148"
                  />
                </div>
                <el-upload
                  v-else
                  list-type="picture-card"
                  :action="uploadUrl"
                  :headers="headers"
                  :on-preview="handlePreview"
                  :on-success="handleSuccess"
                  :before-remove="beforeRemove"
                  :on-exceed="handleExceed"
                  :file-list="fileList"
                  :show-file-list="false"
                  :limit="1"
                  accept=".png, .jpg"
                >
                  <i slot="default" class="el-icon-plus"></i>
                  <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                </el-upload>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="space-around">
          <el-col :span="11">
            <el-form-item label="应用小类" prop="dictDataId">
              <el-select
                class="form-item"
                v-model="appForm.dictDataId"
                placeholder="请选择应用小类"
              >
                <el-option
                  v-for="dict in dict.type.application_small_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="排序" prop="applicationSort">
              <el-input-number class="form-item" v-model="appForm.applicationSort" :min="1"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="space-around">
          <el-col :span="11">
            <el-form-item label="用户名" prop="userName">
              <el-input v-model="appForm.userName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="密 码" prop="password">
              <el-input v-model="appForm.password"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="space-around">
          <el-col :span="23">
            <el-form-item label="链接" prop="link">
              <el-input v-model="appForm.link"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" justify="space-around">
          <el-col :span="23">
            <el-form-item label="描述" prop="description">
              <el-input type="textarea" v-model="appForm.description"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submit()">确 定</el-button>
      </span>
    </el-dialog>

    <!--分类设置弹窗-->
    <el-dialog
      title="分类设置"
      :visible.sync="openTypeList"
      width="60%"
      :close-on-click-modal="false"
      close-on-press-escape
      destroy-on-close
      append-to-body
    >
      <template>
        <div>
          <el-button type="primary" icon="el-icon-plus" @click="handleTypeAdd" v-hasPermi="['system:application:addType']">新增</el-button>
          <el-table v-loading="typeLoading" :data="typeList">
            <el-table-column label="排序" align="center" prop="categorySort"/>
            <el-table-column label="分类名" align="center" prop="categoryName"/>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleTypeUpdate(scope.row)"
                  v-hasPermi="['system:application:editType']"
                >修改
                </el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleTypeDelete(scope.row)"
                  v-hasPermi="['system:application:removeType']"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>
      <span slot="footer" class="dialog-footer">
        <el-button @click="openTypeList = false">取 消</el-button>
        <el-button type="primary" @click="openTypeList = false">确 定</el-button>
      </span>
    </el-dialog>

    <!--新增/修改分类弹窗-->
    <el-dialog
      :title="typeEditTitle"
      :visible.sync="openTypeEdit"
      width="500px"
      :close-on-click-modal="false"
      close-on-press-escape
      destroy-on-close
      @close="resetType"
    >
      <el-form :model="typeForm" :rules="typeRules" ref="typeForm" label-width="80px">
        <el-form-item label="分类名称" prop="categoryName">
          <el-input v-model="typeForm.categoryName"></el-input>
        </el-form-item>
        <el-form-item label="分类排序" prop="categorySort">
          <el-input-number style="width: 380px" v-model="typeForm.categorySort" controls-position="right" :min="1"/>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
            <el-button @click="cancelTypeEdit">取消</el-button>
            <el-button type="primary" @click="submitTypeEdit('typeForm')">提交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import {getAppList, editApp, delApp, getTypeList, editType, delType} from "@/api/system/application.js"
  import {getToken} from "@/utils/auth";

  export default {
    name: "Application",
    dicts: ['sys_app_show', 'application_small_type'],
    data() {
      var checkUpload = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请上传文件'))
        }else {
          callback()
        }
      };

      var checkCategoryId = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请选择应用类型'));
        } else {
          callback();
        }
      };

      var checkDictDataId = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请选择应用小类'));
        } else {
          callback();
        }
      };

      var checkSort = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入排序'));
        } else {
          callback();
        }
      };

      return {
        // 重新渲染表格状态
        refreshTable: true,
        // 遮罩层
        loading: false,
        // 应用数据
        appList: [],
        //全部数据
        total: 0,
        //分类列表
        typeList: [],
        // 是否展开，默认全部折叠
        isExpandAll: false,
        //查询参数
        queryParams: {
          categoryId: null,
          pageNum: 1,
          pageSize: 10,
        },
        //分类设置列表弹窗
        openTypeList: false,
        //分类列表弹窗遮罩
        typeLoading: false,
        //分类编辑弹窗
        openTypeEdit: false,
        typeForm: {
          categoryId: null,
          categoryName: null,
          categorySort: 1
        },
        typeRules: {
          categoryName: [
            {required: true, message: '请输入分类名称', trigger: 'blur'},
          ],
        },
        isAdd: false,
        delId: null,
        typeEditTitle: '新增分类',
        appTitle: '新增应用',
        openAppDlg: false,
        appForm: {
          applicationInfoId: null,
          applicationSort: 1,
          categoryId: null,
          categoryName: "",
          description: "",
          dictDataId: null,
          dictDataName: "",
          icon: "",
          link: "",
          name: "",
          password: "",
          userName: ""
        },
        appRules: {
          name: [
            {required: true, message: '请输入应用名称', trigger: 'blur'},
          ],
          icon: [
            {required: true, validator: checkUpload, trigger: 'change'},
          ],
          categoryId: [
            {required: true, validator: checkCategoryId, trigger: 'change'},
          ],
          dictDataId: [
            {required: true, validator: checkDictDataId, trigger: 'change'},
          ],
          applicationSort: [{
            required: true, validator: checkSort, trigger: 'change'
          }]
        },
        uploadUrl: process.env.VUE_APP_BASE_API + "/application/upload/file", // 上传的图片服务器地址
        headers: {
          Authorization: "Bearer " + getToken()
        },
        fileList: [],
        labelPosition: 'top',
        dialogVisible: false,
        dialogImageUrl: '',
        disabled: false,
        isHover: false
      }
    },
    created() {
      this.getTypes()
    },
    methods: {
      //获取分类
      getCategoryType(id) {
        let name = ""
        this.typeList.forEach(e => {
          if(e.categoryId === id) {
            name = e.categoryName
          }
        })
        return name;
      },

      //获取图片
      getImg(path) {
        let url = process.env.VUE_APP_BASE_API + path
        return url
      },
      //获取分类列表
      getTypes() {
        if (this.openTypeList) {
          this.typeLoading = true
        }
        getTypeList().then(res => {
          if (res.code === 200) {
            this.typeList = res.data
            this.typeLoading = false
            if (this.typeList.length > 0 && (!this.openTypeList || this.isAdd)) {
              this.queryParams.categoryId = this.typeList[0].categoryId ? this.typeList[0].categoryId : null
              this.getList()
              this.isAdd = false
            }
            if (this.delId && this.queryParams.categoryId === this.delId) {
              this.queryParams.categoryId = this.typeList[0] ? this.typeList[0].categoryId : null
              this.delId = null
              if (this.queryParams.categoryId) {
                this.getList()
              } else {
                this.appList = []
              }
            }
          } else {
            this.$message.error(res.msg)
            this.typeLoading = false
            if (this.delId && this.queryParams.categoryId === this.delId) {
              this.queryParams.categoryId = this.typeList[0] ? this.typeList[0].categoryId : null
              this.delId = null
              if (this.queryParams.categoryId) {
                this.getList()
              } else {
                this.appList = []
              }
            }
          }
        }).catch(err => {
          this.$message.error(err)
          this.typeLoading = false
          if (this.delId && this.queryParams.categoryId === this.delId) {
            this.queryParams.categoryId = this.typeList[0] ? this.typeList[0].categoryId : null
            this.delId = null
            if (this.queryParams.categoryId) {
              this.getList()
            } else {
              this.appList = []
            }
          }
        })
      },
      //获取列表数据
      getList() {
        getAppList(this.queryParams).then(res => {
          if (res.code === 200) {
            this.appList = res.rows
            this.total = res.total
            this.loading = false;
          } else {
            this.$message.error(res.msg)
            this.loading = false;
          }
        }).catch(err => {
          this.$message.error(res.err)
          this.loading = false;
        })

      },
      //切换类型
      handleTypeChange(e) {
        this.queryParams.categoryId = e
        this.queryParams.pageNum = 1
        this.getList()
      },
      //多选框
      handleSelectionChange() {

      },
      //新增
      handleAdd() {
        this.appTitle = '新增应用'
        this.openAppDlg = true
      },
      //修改
      handleUpdate(row) {
        this.appTitle = '修改应用'
        this.appForm = JSON.parse(JSON.stringify(row))
        this.appForm.dictDataId = this.appForm.dictDataId.toString()
        this.openAppDlg = true
      },
      //删除
      handleDelete(row) {

        this.$confirm('此操作将永久删除该应用, 是否继续？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delApp(row.applicationInfoId).then(res => {
            if (res.code === 200) {
              this.$message.success('删除成功');
              this.getList()
            } else {
              this.$message.error(res.msg)
            }
          }).catch(err => {
            this.$message.error(err)
          })
        }).catch(() => {});
      },
      //取消
      cancel() {
        this.openAppDlg = false
        this.resetApp()
      },
      //编辑应用
      submit() {
        this.$refs.appForm.validate((valid) => {
          if (valid) {
            editApp(this.appForm).then(res => {
              if (res.code === 200) {
                this.$message.success(this.appForm.applicationInfoId ? '修改成功' : '添加成功')
                this.resetApp()
                this.openAppDlg = false
                this.getList()
              } else {
                this.$message.error(res.msg)
              }
            }).catch(err => {
              this.$message.error(err)
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      //重置app表单
      resetApp() {
        this.appForm = {
          applicationInfoId: null,
          applicationSort: 1,
          categoryId: null,
          categoryName: "",
          description: "",
          dictDataId: null,
          dictDataName: "",
          icon: "",
          link: "",
          name: "",
          password: "",
          userName: ""
        }
      },
      //打开设置分类弹窗
      handleTypeDlyOpen() {
        this.openTypeList = true
        // this.typeLoading = true
      },
      //打添加改分类弹窗
      handleTypeAdd() {
        this.typeEditTitle = '新增分类'
        this.openTypeEdit = true
      },
      //打开修改分类弹窗
      handleTypeUpdate(row) {
        this.typeForm = row
        this.typeEditTitle = '修改分类'
        this.openTypeEdit = true

      },
      //删除分类
      handleTypeDelete(row) {

        this.$confirm('此操作将永久删除该分类, 是否继续？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delType(row.categoryId).then(res => {
            if (res.code === 200) {
              this.$message.success('删除成功')
              this.delId = row.categoryId
              this.getTypes()
            } else {
              this.$message.error(res.msg)
            }
          }).catch(err => {
            this.$message.error(err)
          })
        }).catch(() => {});



      },
      //取消分类编辑
      cancelTypeEdit() {
        this.resetType()
        this.openTypeEdit = false
      },
      //提交分类编辑
      submitTypeEdit() {
        this.$refs['typeForm'].validate((valid) => {
          if (valid) {
            editType(this.typeForm).then(res => {
              if (res.code === 200) {
                this.$message.success(this.typeForm.categoryId ? '修改成功' : '添加成功')
                this.resetType()
                this.openTypeEdit = false
                this.isAdd = true
                this.getTypes()
              } else {
                this.$message.error(res.msg)
              }
            }).catch(err => {
              this.$message.error(err)
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      //重置分类表单
      resetType() {
        this.typeForm = {
          categoryId: null,
          categoryName: null,
          categorySort: 1
        }
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      //移除上传文件
      handleRemove() {
        this.appForm.icon = null
        this.fileList = []
      },
      //上传文件
      handlePreview(file) {
      },
      //上传文件成功
      handleSuccess(response, file, fileList) {
        this.appForm.icon = response.msg
        this.isHover = false
      },
      //限制提示
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      //删除前钩子
      beforeRemove(file, fileList) {
        return this.$confirm(`确定移除 ${file.name}？`);
      }
    }
  }
</script>

<style lang="scss" scoped>
  .search-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom:21px;

    ::v-deep .el-form-item {
      margin-bottom: 0 !important;
    }

    .btn-container {
      display: flex;
      align-items: center;
    }
  }

  .form-item {
    width: 380px;
  }

  .icon-img {
    width: 148px;
    height: 148px;
    position: relative;
    border-radius: 6px;
    /*border: 1px solid #c0ccda;*/
    border: 1px solid rgba(0, 0, 0, .5);
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 12px;
    overflow: hidden;


    .del-cover {
      position: absolute;
      top: 0;
      left: 0;
      width: inherit;
      height: inherit;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #fff;
      font-size: 20px;
      background-color: rgba(0, 0, 0, .5);
      transition: all 0.3s ease-in;
    }

    .hide-cover {
      background-color: rgba(0, 0, 0, 0);
      display: none;

    }
  }

  /*::v-deep .el-form-item {*/
  /*  margin-bottom: 0 !important;*/
  /*}*/

  ::v-deep .el-input--medium, ::v-deep .el-input-number--medium {
    /*width: 360px;*/
  }

  ::v-deep .el-input__inner {
    /*height: 37px;*/
  }

  ::v-deep .el-form-item__content {
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 0 !important;
  }

  ::v-deep .el-pagination__editor {
    width: 50px !important;
  }

  ::v-deep .el-dialog__footer {
    /*display: flex;*/
    /*align-items: center;*/
    /*justify-content: center;*/
    border-top: 1px solid #DDDEDF;
    padding: 20px 30px;
    /*border-radius: 0 0 10px 10px;*/
  }

  ::v-deep .el-dialog__body {
    /*padding: 30px;*/
    /*border-radius: 10px 10px 0 0;*/
  }

  ::v-deep .el-dialog__header {
    padding: 20px 30px 10px;
    /*border-radius: 10px 10px 0 0;*/
  }

  ::v-deep .el-dialog__title {
    font-family: PingFangSC-Medium;
    font-size: 16px;
    color: #1F2329;
    letter-spacing: 0;
  }

  ::v-deep .el-dialog {
    border-radius: 10px;
  }

  ::v-deep .el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label:before {
    content: '' !important;
  }

  ::v-deep .el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label:after {
    content: '*';
    color: red;
    margin-left: 4px;
  }

  ::v-deep .el-form-item {
    margin-bottom: 0 !important;
  }
</style>
